package com.yixun.controller;

import com.yixun.service.RedisService;
import com.yixun.util.ResponseModel;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author 吕兵星
 * @date 2021/6/26 15:23
 */
@RestController
public class FileController {
    @Resource
    private RedisService redisService;
    @Value("${file.uploadFile}")
    public  String UPLOAD_FILE;
    /*上传文件时，将文件路径 储存在redis中 若取消了提交 或者最终没有提交 定时任务会在周期类 删除该文件 以节省空间*/
    @Value("${file.redis_key}")
    public   String FILES_TO_BE_DELETED;
    SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/dd/");
    @PostMapping("upload")
    public Map<String, Object> upload(MultipartFile file, HashMap<String,Object> map){
        String formatDateFilePath = sdf.format(new Date());
        String path = UPLOAD_FILE + formatDateFilePath;
        String newName=UUID.randomUUID().toString().replace("-","")+"_"+file.getOriginalFilename();
        File folder = new File(path);
        if (!folder.exists()){
            folder.mkdirs();
            
        }
        try {
            file.transferTo(new File(folder,newName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        map.put("url","/file/"+formatDateFilePath+newName);
        redisService.setFilesToBeDeleted(FILES_TO_BE_DELETED,formatDateFilePath+newName);
        return ResponseModel.getModel("success", "200", map);
    }
    
}
